<template>
  <Dialog v-model="dialogVisible2" title="上传视频" width="800" max-height="300">
    <uploader
      :options="options"
      :file-status-text="statusText"
      class="uploader-example"
      ref="uploaderRef"
      :autoStart="false"
      @file-added="onFileAdded"
      @file-complete="fileComplete"
      @complete="complete"
      @file-success="onFileSuccess"
    />
    <template #footer>
      <BaseButton type="primary" @click="save"> 保存</BaseButton>
      <BaseButton @click="dialogVisible2 = false">返回</BaseButton>
    </template>
  </Dialog>
</template>

<script>
import { nextTick, ref, onMounted, watch, defineProps } from 'vue'
import { Dialog } from '@/components/Dialog'
// import { MINIO_BUCKET } from '@/constants'
import {
  addBatchSysVideoApi,
  completeMultipartUpload,
  createMultipartUpload
} from '@/api/resLibrary/video'
import { useUserStore } from '@/store/modules/user'
export default {
  components: {
    Dialog
  },

  props: ['currentRow'],
  setup(props) {
    const userStore = useUserStore()
    const uploaderRef = ref(null)
    const dialogVisible2 = ref(false)
    const reslist = ref([])
    const options = {
      target: function (file, chunkFile, mode) {
        const key = 'chunk_' + chunkFile.offset // 键值 用于获取分块链接URL
        return file.chunkUrlData[key]
      },
      testChunks: false,
      chunkSize: 5 * 1024 * 1024,

      // 强制所有块小于或等于 chunkSize。否则，最后一个块将大于或等于chunkSize。(默认: false)
      forceChunkSize: true,
      // 包含在带有数据的多部分 POST 中的额外参数。这可以是一个对象或一个函数。如果是一个函数，
      // 它将被传递一个 Uploader.File、一个 Uploader.Chunk 对象和一个 isTest 布尔值（默认值{}：）
      query: function (file, chunkFile, mode) {
        const data = { partNumber: chunkFile.offset + 1 }
        return data
      },
      uploadMethod: 'PUT',
      //  当上传的时候所使用的是方式，可选 multipart、octet，默认 multipart，参考 multipart vs octet。
      // MiniO 的分片不能使用表单
      method: 'octet',
      //  处理请求参数，默认 function (params) {return params}，一般用于修改参数名字或者删除参数。0.5.2版本后，
      processParams: function (params) {
        return {}
      }
    }
    const attrs = {
      accept: 'image/*'
    }
    const statusText = {
      success: '成功了',
      error: '出错了',
      uploading: '上传中',
      paused: '暂停中',
      waiting: '等待中'
    }
    const complete = () => {
      console.log('complete', arguments)
    }
    const fileComplete = () => {
      console.log('file complete', arguments)
    }
    const row = ref(null)

    onMounted(() => {
      nextTick(() => {
        window.uploader = uploaderRef.value.uploader
      })
    })
    const isShowUploadBigFileModel = () => {
      dialogVisible2.value = true
    }
    const getUploadFileName = (fileName) => {
      const userId = userStore.getUserInfo.id
      const realName = userStore.getUserInfo.realName
      const fileNameExt = fileName.substring(fileName.length - 3)
      const fileNameMain = fileName.substring(0, fileName.length - 4)
      const fileNameDh = fileNameMain.replace(/\s{1,}|\./g, '')
      const uploadFileName =
        realName +
        '_' +
        userId +
        '/' +
        props.currentRow.code +
        '/' +
        fileNameDh +
        '/' +
        fileNameDh +
        '.' +
        fileNameExt
      console.log(uploadFileName, 'uplodad')
      return uploadFileName
    }
    const onFileAdded = async (file) => {
      const fileName = file.name // 文件名
      const chunkSize = file.chunks.length // 分片数
      const fileNameMain = getUploadFileName(fileName)
      // 请求后台返回每个分块的上传链接
      // eslint-disable-next-line no-unused-vars
      const aa = await createMultipartUpload({
        fileName: fileNameMain,
        chunkSize: chunkSize
        // bucketName: MINIO_BUCKET
      })
      file.chunkUrlData = aa.data
    }

    // 单个文件上传成功
    const onFileSuccess = (rootFile, file, message) => {
      // 调用后台合并文件
      const fileName = file.name // 文件名
      const fileNameMain = getUploadFileName(fileName)
      const uploadId = file.chunkUrlData.uploadId // uploadId
      completeMultipartUpload({
        objectName: fileNameMain,
        uploadId: uploadId
        // bucketName: MINIO_BUCKET
      })
        .then(function (response) {
          reslist.value.push(response.data)
          console.log(response)
        })
        .catch(function (error) {
          console.log(error)
        })
    }
    const save = () => {
      const aa = {}
      aa.videoTypeId = props.currentRow.id
      aa.fileUrlList = reslist.value
      addBatchSysVideoApi(aa).then(() => {
        reslist.value = []
        dialogVisible2.value = false
      })
    }
    return {
      uploaderRef,
      options,
      attrs,
      statusText,
      complete,
      fileComplete,
      dialogVisible2,
      isShowUploadBigFileModel,
      onFileSuccess,
      onFileAdded,
      save
    }
  }
}
</script>

<style>
.uploader-example {
  width: 670px;
  padding: 15px;
  margin: 10px 10px;
  font-size: 12px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
}

.uploader-example .uploader-btn {
  margin-right: 4px;
}

.uploader-example .uploader-list {
  max-height: 300px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
